package com.liangtian.mdm.system.menu.model;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@SuppressWarnings("unchecked")
public class TreeBuilder {

    public static List<MenuShow> buildListToTree(List<MenuShow> dirs) {
        List<MenuShow> roots = findRoots(dirs);
        List<MenuShow> notRoots = (List<MenuShow>) CollectionUtils.subtract(dirs, roots);
        for (MenuShow root : roots) {
            root.setNextMenu(findChildren(root, notRoots));
        }
        return roots;
    }

    public static List<MenuShow> findRoots(List<MenuShow> allMenuShows) {
        List<MenuShow> results = new ArrayList<MenuShow>();
        for (MenuShow MenuShow : allMenuShows) {
            if ("0".equals(MenuShow.getSuper_id()))
                results.add(MenuShow);
        }
        Collections.sort(results);
        return results;
    }

    public static List<MenuShow> findChildren(MenuShow root, List<MenuShow> allMenuShows) {

        List<MenuShow> children = new ArrayList<MenuShow>();
        for (MenuShow comparedOne : allMenuShows) {
            if (comparedOne.getSuper_id().equals(root.getMenu_id())) {
                children.add(comparedOne);
            }
        }
        Collections.sort(children);

        List<MenuShow> notChildren = (List<MenuShow>) CollectionUtils.subtract(allMenuShows, children);
        for (MenuShow child : children) {
            List<MenuShow> tmpChildren = findChildren(child, notChildren);
            // if (tmpChildren.size() == 0) child.setLeaf(true);
            Collections.sort(tmpChildren);
            child.setNextMenu(tmpChildren);
        }
        return children;
    }

}
